package com.gomeplus.diamond;

import com.taobao.diamond.manager.DiamondManager;
import com.taobao.diamond.manager.ManagerListener;
import com.taobao.diamond.manager.impl.DefaultDiamondManager;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.locks.ReentrantLock;

public class DiamondConfig {
    private static final Logger logger = LoggerFactory.getLogger(DiamondConfig.class);

    private static String dataId;
    private static String groupId;
    private static String encode = "GBK";

    private static PropertiesConfiguration prop;
    private static ReentrantLock lock = new ReentrantLock();
    private static long timeout = 10000L;

    private static final String CONF_PATH = "props/diamond-config.properties";

    private static String diamondURL = "";

    /**
     * 初始化diamond
     *
     * @param dataId
     */
    public static void init(String dataId) {
        preper(dataId);
        load();

    }

    /**
     * 初始化diamond
     *
     * @param p_dataId
     */
    public static void preper(String p_dataId) {
        diamondURL = new PropertiesLoader(CONF_PATH).getProperty("diamond.url");
        groupId = new PropertiesLoader(CONF_PATH).getProperty("groupId");
        //dataId = new PropertiesLoader(CONF_PATH).getProperty("dataId");
        dataId = p_dataId;
        System.out.println("groupId======" + groupId);
        System.out.println("dataId======" + dataId);
        System.out.println("CONF_PATH======" + CONF_PATH);
        System.out.println("diamondURL======" + diamondURL);
    }

    public static void load() {
        if (!StringDiamondUtils.areNotEmpty(new String[]{dataId, groupId})) {
            throw new RuntimeException("appName or groupName can't is null or empty");
        }
        DiamondManager manager = new DefaultDiamondManager(groupId, dataId, new ManagerListener() {
            @Override
            public Executor getExecutor() {
                return null;
            }

            @Override
            public void receiveConfigInfo(String configInfo) {
                logger.info("config reloaded......");
                addData(configInfo);
            }
        }, diamondURL);
        addData(manager.getAvailableConfigureInfomation(timeout));
    }

    private static void addData(String config) {

        if (StringDiamondUtils.isNullorBlank(config)) {
            return;
        }

        if (logger.isDebugEnabled()) {
            logger.debug(config);
        }

        InputStream in = null;
        try {
            in = new ByteArrayInputStream(config.getBytes(encode));
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        try {
            lock.lock();

            PropertiesConfiguration temp = new PropertiesConfiguration();
            temp.setEncoding(encode);
            temp.load(in);
            prop = temp;
        } catch (ConfigurationException e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
            }
            lock.unlock();
        }
    }

    public static String getProperty(String key, String defaultValue) {
        return prop.getString(key, defaultValue);
    }

    public static String getString(String key) {
        return prop.getString(key);
    }

    public static Integer getInt(String key, int defaultVal) {
        return Integer.valueOf(prop.getInt(key, defaultVal));
    }

    public static Double getDouble(String key, Double defaultVal) {
        return prop.getDouble(key, defaultVal);
    }

    public static boolean getBoolean(String key, boolean defaultVal) {
        return prop.getBoolean(key, defaultVal);
    }

    public static List<Object> getList(String key) {
        return prop.getList(key);
    }

    public static Object getProperty(String name) {
        return prop.getProperty(name);
    }

    public static void setDataId(String dataId) {
        DiamondConfig.dataId = dataId;
    }

    public static void setGroupId(String groupId) {
        DiamondConfig.groupId = groupId;
    }

    public static void setEncode(String encode) {
        DiamondConfig.encode = encode;
    }
}